<script lang="ts" setup>
import * as XLSX from 'xlsx'
import { ElMessage, ElTable } from 'element-plus'
import { reactive, ref } from 'vue'
import { GetPintuanList, PostModifyStatus } from '@/api/modules/pintuan'
import GetCacheData from '@/store/modules/NewPageCache'

const imgDomain = 'https://img1.eprhan.cc'
const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('pintuan').currentPage
const loading = ref(false)
const total = ref(0) // 总数据数
const route = useRoute()
const router = useRouter()

// 数据列表
const dataList = reactive({
  list: [],
})

// 查询表单
const findFrom = ref({
  ...(cacheData.GetCacheData('pintuan').fromData),
})

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('pintuan').currentSize)
  cacheData.SetCacheData('pintuan', PageNum, cacheData.GetCacheData('pintuan').currentSize, findFrom.value)
}

// 获取商品业绩数据
async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.OrderNo && ({ OrderNo: findFrom.value.OrderNo })),
    ...(findFrom.value.ProductId && ({ ProductId: findFrom.value.ProductId })),
    ...(findFrom.value.Flag !== '~' && ({ Flag: findFrom.value.Flag })),
    ...(findFrom.value.AddTime?.length > 0 && {
      StartAddTime: findFrom.value.AddTime[0],
      EndAddTime: findFrom.value.AddTime[1],
    }),
  }

  await GetPintuanList(params).then((res: any) => {
    // console.log(res.data.items)
    if (res.succeeded) {
      dataList.list = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
      loading.value = false
    }
  }).catch(() => {
    ElMessage.error('获取数据失败。')
    loading.value = false
  })
}

async function ExportExcel() {
  const params = {
    PageIndex: 1,
    PageSize: 10000,
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.ProductId && ({ ProductId: findFrom.value.ProductId })),
    ...(findFrom.value.Flag !== '~' && ({ Flag: findFrom.value.Flag })),
    ...(findFrom.value.AddTime?.length > 0 && {
      StartAddTime: findFrom.value.AddTime[0],
      EndAddTime: findFrom.value.AddTime[1],
    }),
  }

  const excelData = await GetPintuanList(params)

  const headerMapping = {
    timeUnit: `时间（${findFrom.value.TimeWd === '1' ? '天' : findFrom.value.TimeWd === '2' ? '周' : '月'}）`,
    totalAmount: '成交金额',
    validTotalAmount: '去退成交金额',
    buyersNumber: '下单人数',
    averageAmount: '客单价（成交金额/下单人数）',
    refundAmount: '退款金额',
    refundProbability: '退款率（退款金额/成交金额）',
  } as { [key: string]: string }

  // console.log(excelData.data)

  // 映射数据和合并order对象
  const newData = excelData.data.map((item: { [key: string]: any }) => {
    if (findFrom.value.orderStatus === '2') {
      const newItem = {
        productId: item.productInfo?.productId, // 将productId移动到前面
        productName: item.productInfo?.productName,
        salePrice: item.productInfo?.salePrice,
        // 复制其他属性到新对象
        ...item,
      }
      // 更新item为新的对象
      item = newItem

      delete item.productInfo
    }

    return Object.keys(item).reduce((newItem, key) => {
      (newItem as { [key: string]: any })[headerMapping[key] || key] = item[key]
      return newItem
    }, {})
  })
  // console.log(newData)
  // console.log('订单数量', newData)

  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(newData)
  // 设置列宽
  ws['!cols'] = [{ wch: 30 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 30 }, { wch: 20 }, { wch: 20 }, { wch: 15 }, { wch: 15 }, { wch: 30 }]
  // XLSX.utils.sheet_add_aoa(ws, [Object.values(headerMapping)], { origin: 'A1' })
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  if (findFrom.value.orderStatus === '1') {
    XLSX.writeFile(wb, '业绩统计数据.xlsx')
  }
  else {
    XLSX.writeFile(wb, '商品统计数据.xlsx')
  }
}

const shortcuts = [
  {
    text: '今天',
    value: () => {
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: '近一周',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '近一月',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '近一年',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date()
      start.setFullYear(start.getFullYear() - 1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
]

const dialogTableVisible = ref(false)
const tuanDetailList = ref([])
function SetTuanDetail(Detail: any) {
  tuanDetailList.value = Detail.tuanDetail
  dialogTableVisible.value = true
}

function SkipOrder(tuanId: string) {
  router.push({
    name: 'RetailOrder',
    query: {
      tuanId,
    },
  })
}

const statusDialog = ref(false)
const StatusObj = reactive(
  {
    idList: [0],
    flag: '',
  },
)
const StatusFlag = ref(0)
function ModifyStatus(row: any) {
  StatusObj.idList = [row.id]
  StatusFlag.value = row.flag
  statusDialog.value = true
}
function SetStatusFlag() {
  const params = {
    ...StatusObj,
  }
  PostModifyStatus(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('修改成功')
      statusDialog.value = false
      GetDataList(cacheData.GetCacheData('pintuan').currentPage, cacheData.GetCacheData('pintuan').currentSize)
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
    }
  })
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('pintuan', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('pintuan').currentSize)
  cacheData.SetCacheData('pintuan', val, cacheData.GetCacheData('pintuan').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('pintuan').currentPage || 1
})

onMounted(() => {
  if (route.query.productId) {
    findFrom.value.ProductId = route.query.productId
  }
  else {
    findFrom.value.ProductId = ''
  }
  GetDataList(cacheData.GetCacheData('pintuan').currentPage, cacheData.GetCacheData('pintuan').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="参团用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入参团用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="商品ID">
                <el-input v-model="findFrom.ProductId" placeholder="请输入商品ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="订单编号">
                <el-input v-model="findFrom.OrderNo" placeholder="请输入订单编号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="开团状态">
                <el-select v-model="findFrom.Flag" placeholder="请选择开团状态">
                  <el-option label="全部" value="~" />
                  <el-option label="拼团中" :value="0" />
                  <el-option label="拼团成功" :value="1" />
                  <el-option label="拼团失败" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="下单时间">
                <el-date-picker
                  v-model="findFrom.AddTime" type="daterange" clearable value-format="YYYY-MM-DD HH:mm:ss"
                  range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
                  :shortcuts="shortcuts"
                />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="ExportExcel">
          导出
        </el-button>
      </div>
      <ElTable v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="团ID" width="100" />
        <el-table-column align="center" prop="leaderSubscriber.userId" label="用户Id" width="100" />
        <el-table-column align="center" prop="leaderSubscriber.scOpenId" label="用户OpenId" width="300" />
        <el-table-column align="center" prop="leaderSubscriber.UnionId" label="用户UnionId" width="300" />
        <el-table-column align="center" prop="leaderSubscriber" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.leaderSubscriber">
              未授权
            </div>
            <el-tooltip
              v-else
              class="box-item"
              effect="dark"
              :content="scope.row.leaderSubscriber?.scOpenId"
              placement="top"
            >
              <div class="user-name">
                <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.leaderSubscriber?.userAvatar" />
                <div>
                  <p style="margin: 0;">
                    {{ scope.row.leaderSubscriber?.userNickName }}
                  </p>
                  <span>
                    {{ scope.row.leaderSubscriber?.userPhone }}
                  </span>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="product.productId" label="商品ID" width="100" />
        <el-table-column header-align="center" prop="product.productName" label="商品名称" min-width="440" show-overflow-tooltip />
        <el-table-column align="center" prop="product" label="商品封面" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.product?.cdnProductPhotoPic" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="product.salePrice" label="商品零售价" min-width="120" />
        <el-table-column align="center" prop="tuanMaxCount" label="成团数" min-width="120" />
        <el-table-column align="center" prop="tuanHasCount" label="已参团数" min-width="120" />
        <el-table-column align="center" prop="flag" label="类型" width="100">
          <template #default="scope">
            <el-tag>
              {{ scope.row.flag === 0 ? '拼团中'
                : scope.row.flag === 1 ? '拼团成功'
                  : scope.row.flag === 2 ? '拼团失败' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="desp" label="描述" width="240" />
        <el-table-column align="center" prop="startTime" label="开始时间" min-width="240" />
        <el-table-column align="center" prop="endTime" label="结束时间" min-width="240" />
        <el-table-column align="center" prop="addTime" label="开团时间" min-width="240" />
        <el-table-column align="center" prop="updateTime" label="最后更新时间" min-width="240" />
        <el-table-column align="center" label="操作" fixed="right" min-width="240">
          <template #default="scope">
            <div style="line-height: 42px;">
              <el-button type="primary" @click="SetTuanDetail(scope.row)">
                查看团明细
              </el-button>
              <el-button type="primary" @click="SkipOrder(scope.row.id)">
                查询订单
              </el-button>
              <el-button type="success" :disabled="scope.row.flag === 1" @click="ModifyStatus(scope.row)">
                更改状态
              </el-button>
            </div>
          </template>
        </el-table-column>
      </ElTable>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('pintuan').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <!-- 团明细列表 -->
    <el-dialog v-model="dialogTableVisible" title="团明细" width="800">
      <ElTable :data="tuanDetailList">
        <el-table-column align="center" prop="id" label="团ID" width="100" />
        <el-table-column align="center" prop="subscriber.userId" label="用户Id" width="100" />
        <el-table-column align="center" prop="subscriber.scOpenId" label="用户OpenId" width="300" />
        <el-table-column align="center" prop="subscriber.UnionId" label="用户UnionId" width="300" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriber">
              未授权
            </div>
            <el-tooltip
              v-else
              class="box-item"
              effect="dark"
              :content="scope.row.subscriber?.scOpenId"
              placement="top"
            >
              <div class="user-name">
                <el-avatar :size="40" style="margin-right: 10px;" :src="imgDomain + scope.row.subscriber?.userAvatar" />
                <div>
                  <p style="margin: 0;">
                    {{ scope.row.subscriber?.userNickName }}
                  </p>
                  <span>
                    {{ scope.row.subscriber?.userPhone }}
                  </span>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="flag" label="类型" width="100">
          <template #default="scope">
            <el-tag>
              {{ scope.row.flag === 0 ? '未下单'
                : scope.row.flag === 1 ? '下单成功' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="desp" label="描述" width="240" />
        <el-table-column align="center" prop="addTime" label="参团时间" min-width="120" />
      </ElTable>
    </el-dialog>

    <!-- 修改状态 -->
    <el-dialog v-model="statusDialog" title="修改状态" width="500">
      <el-form :model="StatusObj">
        <el-form-item label="状态">
          <el-select v-model="StatusObj.flag" placeholder="请选择要修改的状态">
            <el-option v-if="StatusFlag !== 0" label="拼团中" :value="0" />
            <el-option label="拼团成功" :value="1" />
            <el-option v-if="StatusFlag !== 2" label="拼团失败" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetStatusFlag">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
